<template>
  <div>
    <!--搜索查询-->
    <el-row>
      <!-- <el-col :span="">&nbsp;</el-col> -->
      <el-col :span="4"
        ><el-input
          v-model="searchForm.name"
          size="mini"
          clearable
          placeholder="请输入广告名称"
        ></el-input
      ></el-col>
      <el-col :span="2"
        ><el-button
          type="primary"
          size="mini"
          @click="search()"
          icon="el-icon-search"
          v-has="'advertise:search'"
          >搜索</el-button
        ></el-col
      >
      <el-col :span="2"
        ><el-button
          type="primary"
          size="mini"
          @click="handlerAdd()"
          v-has="'advertise:add'"
          icon="el-icon-circle-plus"
          >添加</el-button
        ></el-col
      >
      <el-col :span="2"
        ><el-button
          type="primary"
          size="mini"
          @click="flush()"
          v-has="'advertise:flush'"
          icon="el-icon-refresh"
          >刷新</el-button
        ></el-col
      >
    </el-row>

    <el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          prop="name"
          label="广告名称"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="posName"
          label="广告位置"
          align="center"
          width="200"
        >
        </el-table-column>

        <el-table-column label="图片">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.pic"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" width="150" label="开始时间">
        </el-table-column>
        <el-table-column prop="endTime" width="150" label="结束时间">
        </el-table-column>
        <el-table-column
          prop="status"
          :formatter="statusFormat"
          width="150"
          label="显示状态"
        >
        </el-table-column>
        <el-table-column prop="note" width="150" label="备注">
        </el-table-column>
        <el-table-column prop="clickCount" width="150" label="点击数">
        </el-table-column>
        <el-table-column prop="url" width="150" label="url连接">
        </el-table-column>
        <el-table-column
          prop="maxCount"
          width="150"
          label="可承受最大数量"
          v-if="false"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="250px;"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              v-has="'advertise:onoff'"
              @click="changeStatus(scope.$index, scope.row)"
              >{{ scope.row.status == 0 ? "上线" : "下线" }}</el-button
            >
            <el-button
              size="mini"
              v-has="'advertise:modify'"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              v-has="'advertise:del'"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <!--分页插件-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 3, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>

    <!--广告添加/更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" align="left">
      <el-form :model="form" ref="form">
        <el-form-item
          label="广告名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="广告备注"
          prop="note"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.note" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startTime"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="结束时间"
          prop="endTime"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择过期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片" prop="pic" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:12066/user/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="pic"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-input
            v-if="condition"
            v-model="form.pic"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="广告状态"
          prop="status"
          :label-width="formLabelWidth"
        >
          <el-radio v-model="form.status" label=1>上线</el-radio>
          <el-radio v-model="form.status" label=0>下线</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tpcount: "",
      btcount: "",
      condition: "",
      data: [], //权限树数组对象
      defaultProps: {
        //父对象传值
        children: "children",
        label: "label",
      },
      title: "广告添加",
      formLabelWidth: "120px",
      nodeChecked: [], //勾选项目数组对象
      tableData: [],
      currentPage: 1, //页码 第几页
      pageSize: 5, //每页显示数量
      total: 100, //总条数
      searchForm: { name: "" }, //搜索form表单
      dialogFormVisible: false, //是否显示对话框  默认是不显示
      form: {}, //form表单对象
      roleId: 0, // 角色ID
      onlineStatus: "上线", //上下操作按钮
      options: [], //广告位置下拉框数据
      imgUrl: "",
    };
  },
  created() {
    //初始化方法 类似于jquery  $({})
    this.loadData();
    this.loadOptions();
  },
  //所有函数
  methods: {
    //加载数据
    loadData() {
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      _this.$http
        .post("/advertise/queryByPage", {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: {
            name: this.searchForm.name,
          },
        })
        .then(function (response) {
          if (response.data.code == 200) {
            _this.tableData = response.data.data.records;
            _this.total = response.data.data.total;
            //_this.options = response.data.data.list;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
    //加载下拉框数据
    loadOptions() {
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      _this.$http
        .post("/advertisePosition/queryByPage", {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: {}
        })
        .then(function (response) {
          if (response.data.code == 200) {
            _this.options = response.data.data.records;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
    handleAvatarSuccess(response, file, fileList) {
      //图片回显
      this.imgUrl = response.data;
      //alert(response);
      //alert(JSON.stringify(response));
      this.form.pic = response.data;
      // this.form.fileName=file.response.oldFileName;
      // this.form.filePath=file.response.newFilePath;
    },
    //上传前图片类型和大小判断
    beforeAvatarUpload(file) {
      const FILE_NAME = file.name;
      if (
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".bmp" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".jpg" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".png"
      ) {
        this.$message.warning("仅支持.bmp.jpg.png文件");
        return false;
      }
      // const isJPG = file.type === 'image/jpeg';
      const isLt3M = file.size / 1024 / 1024 < 3;

      /* if (!isJPG) {
              this.$message.error('上传头像图片只能是 JPG 格式!');
          }*/
      if (isLt3M) {
        this.file = file;
        return true;
      }
      this.$message.warning("请上传不超过3M的文件.");
      return false;
    },
    //处理更新
    handleEdit(index, row) {
      var _this = this;
      //row  当前行数据 如果是第一行  row = {deptId:1,deptName:'管理部'把一行数据赋值给form赋值,description:'店长的事',status:1}
      console.log(index, row);
      //显示对话框
      _this.dialogFormVisible = true;
      //指定对话框标题
      _this.title = "广告更新";
      //把一行数据赋值给form赋值
      _this.form = row;
      //把数字1变为字符串1
      _this.form.platform = row.platform + "";
      _this.form.minPonint = row.minPoint + "";
      _this.imgUrl = row.pic;
    },
    //处理添加
    handlerAdd() {
      this.imgUrl = "";
      //显示对话框
      this.dialogFormVisible = true;
      //指定对话框标题
      this.title = "广告添加";
      //让form表单重新赋空值
      this.form = {};
    },
    statusFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "下线" : "上线";
    },
    //处理每页数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //让每页数量发生变化
      this.pageSize = val;
      //重载数据
      this.loadData();
    },
    //处理当前页变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      //让每页数量发生变化
      this.currentPage = val;
      //重载数据
      this.loadData();
    },
    //查询
    search() {
      this.loadData();
    },
    //刷新
    flush() {
      this.currentPage = 1;
      this.pageSize = 5;
      this.loadData();
    },
    //取消按钮
    dialogFormVisiblExit() {
      this.form = "";
      this.dialogFormVisibleAdd = false;
    },
    //改变上线状态
    changeStatus(index, row) {
      if (row.status == 0) {
        var _this = this;
        this.$http.get("/advertise/queryCount").then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            if (row.posName == "首页头部轮播") {
              if (response.data.data.topCount >= row.maxCount) {
                _this.$message.error("添加数已达最大上限值");
              } else {
                var tempStatus = row.status == 0 ? 1 : 0;
                //改变状态
                _this.$http
                  .post("/advertise/edit", { id: row.id, status: tempStatus })
                  .then(function (response) {
                    if (response.data.code == 200) {
                      _this.$message({
                        message: "恭喜你，这是一条成功消息",
                        type: "success",
                      });
                      _this.loadData();
                    }
                  });
              }
            } else if (row.posName == "首页底部部图") {
              if (response.data.data.buttonCount >= row.maxCount) {
                _this.$message.error("添加数已达最大上限值");
              } else {
                var tempStatus = row.status == 0 ? 1 : 0;
                //改变状态
                _this.$http
                  .post("/advertise/edit", { id: row.id, status: tempStatus })
                  .then(function (response) {
                    if (response.data.code == 200) {
                      _this.loadData();
                      _this.$message({
                        message: "恭喜你，这是一条成功消息",
                        type: "success",
                      });
                    }
                  });
              }
            }
          }
        });
      } else if (row.status == 1) {
        var _this = this;
        var tempStatus = row.status == 0 ? 1 : 0;
        //改变状态
        _this.$http
          .post("/advertise/edit", { id: row.id, status: tempStatus })
          .then(function (response) {
            if (response.data.code == 200) {
              _this.loadData();
              _this.$message({
                message: "恭喜你，这是一条成功消息",
                type: "success",
              });
            }
          });
      }
    },
    //处理逻辑删除
    handleDelete(index, row) {
      console.log(index, row);
      //确认框提示
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //让_this等于当前vue对象
          var _this = this;
          // alert(111);
          //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
          _this.$http
            .delete("/advertise/deleteById?id=" + row.id) //指定请求的url及参数  get
            .then(function (response) {
              //正确返回对象的处理
              // handle success
              console.log(response);
              //JSON.stringify   把json转换为json字符串，方便查看
              console.log(JSON.stringify(response));
              //直接使用this 会指 $http对象  错误
              // this.tableData
              //判断返回值是否正确
              if (response.data.code == 200) {
                //提示添加成功
                _this.$message({
                  message: "恭喜你，这是一条成功消息",
                  type: "success",
                });
                //重新加载数据
                _this.loadData();
              } else {
                //错误提示信息
                _this.$message.error("错了哦，这是一条错误消息");
              }
            })
            .catch(function (error) {
              //错误的处理
              // handle error
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //处理提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var url = "";
          if (this.title == "广告添加") {
            url = "/advertise/add";
          } else {
            url = "/advertise/edit";
          }
          //让_this等于当前vue对象
          var _this = this;
          //alert(JSON.stringify(this.form));
          // alert(111);
          //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
          _this.$http
            .post(url, this.form) //指定请求的url及参数  get
            .then(function (response) {
              //正确返回对象的处理
              // handle success
              console.log(response);
              //JSON.stringify   把json转换为json字符串，方便查看
              console.log(JSON.stringify(response));
              //直接使用this 会指 $http对象  错误
              // this.tableData
              //判断返回值是否正确
              if (response.data.code == 200) {
                //关闭弹框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
                  message: "恭喜你，这是一条成功消息",
                  type: "success",
                });
                //重新加载数据
                _this.loadData();
              } else {
                //错误提示信息
                _this.$message.error("错了哦，这是一条错误消息");
              }
            })
            .catch(function (error) {
              //错误的处理
              // handle error
              console.log(error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 178px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
